<template>
<div>
    <van-nav-bar
  title="黑马头条-登录"
  fixed/>
    <div class="top">
    <van-form @submit="onSubmit">
  <van-field
    v-model="user.mobile"
    required
    name="mobile"
    label="手机号码"
    placeholder="请输入手机号码"
    :rules="[{ required: true, message: '请输入正确的手机号',pattern:/^1[3-9]\d{9}$/ }]"
  />

  <van-field
    v-model="user.code"
    required
    type="number"
    name="code"
    label="验证码"
    placeholder="请输入正确的验证码"
    :rules="[{ required: true, message: '请填写6位验证码' ,pattern:/^\d{6}$/}]"
  />

  <div style="margin: 16px;">
    <van-button round block type="info" native-type="submit" :disabled='isLogin'  :loading='isLogin'  loading-text="登录中..." >登录</van-button>
  </div>
</van-form>
    </div>
    </div>
</template>

<script>
import { loginAPI } from '@/api'
import Notify from '@/ui/Notify'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      isLogin: false,
      user: {
        mobile: '13900000000',
        code: '246810'
      }
    }
  },
  methods: {
    ...mapMutations(['setRefreshToken', 'setToken']),
    async onSubmit (values) {
      this.isLogin = true
      const [err, res] = await loginAPI(values)
      if (err) Notify({ type: 'danger', message: '验证码或者手机号错误' })
      else {
        Notify({
          type: 'success',
          message: '登录成功',
          onClose: () => {
            this.$router.push({
              name: 'Layout'
            })
          }
        })
        this.setRefreshToken(res.data.data.refresh_token)
        this.setToken(res.data.data.token)
      }
      this.isLogin = false
    }
  }
}
// 目标3：把登录成功的token值，保存在SessionStorage一份，保存在vue里一份

</script>

<style lang="less" scoped>
.top{
    padding-top: 46px ;
}
</style>
